<template>
  <div class="game2B">
    <audio id="errorSound"
      src="https://ziyuan.windbless.top/sounds/lakk/%E5%BE%88%E6%8A%B1%E6%AD%89%EF%BC%8C%E6%B6%82%E8%89%B2%E9%94%99%E8%AF%AF%EF%BC%8C%E8%AF%B7%E6%B6%82%E4%B8%8A%E6%AD%A3%E7%A1%AE%E7%9A%84%E9%A2%9C%E8%89%B2%E3%80%82.mp3"></audio>
    <!-- <input type="text" v-model="imgurl" @change="loadImage" placeholder="放url"/>
      <input type="color" v-model="replacementColor" />
      <button @click="downloadImage">下载</button> -->
    <canvas ref="canvas" width="500" height="300" @click="pickColor"></canvas>
    <div class="desc">请选择颜色, 然后可以上色</div>
    <div class="btns">
      <div @click="choosecolor(index)" :style="`background-color:${item};`" class="item"
        v-for="(item, index) in chooseitems">
      </div>
    </div>
  </div>
</template>

<script setup>
import api from '@/api/user.js'
import config from '@/config/config.js'
import { ref, onMounted, defineProps, defineEmits } from 'vue';
const emits = defineEmits(['next']);
import { useAuthStore } from '@/store/index.ts'
import { message } from 'ant-design-vue';
const store = useAuthStore();
// 定义颜色选项
const chooseitems = ref(["#f1a2b9", "#78b566", "#fbe8d3"]);
const colornum = ref(0);
const colormap = new Map();
// 图像 URL
const imgurl = ref('');

// 引用 canvas 和上下文
const canvas = ref(null);
const ctx = ref(null);

// 图像和图像数据的引用
const image = ref(null);
const originalImageData = ref(null);

// 替换颜色的默认值
const replacementColor = ref('');
const num = ref(0);
// 挂载后加载图像并获取上下文
onMounted(() => {

  ctx.value = canvas.value.getContext('2d');

  imgurl.value = '/img' + props.imgSrc;
  getoptions();
  loadImage();
  console.log(colormap);
});
//处理选项数据
const getoptions = () => {
  let correctanswer = [];
  let answer = [];
  for (let item of props.correctanswer.split(',')) {
    correctanswer.push(item.split('->')[1])
    answer.push(item.split('->')[0])
    colormap.set(item.split('->')[0], item.split('->')[1])
  }
  chooseitems.value = correctanswer;
}
// Define props
const props = defineProps({
  imgSrc: {
    type: String,
    required: true
  },
  correctanswer: {
    type: String,
    required: true
  }
});



// 选择颜色的方法
const choosecolor = (item) => {
  replacementColor.value = chooseitems.value[item];
};

// 加载图像到 canvas 上
const loadImage = () => {
  let url = imgurl.value;
  console.log(url);
  image.value = new Image();
  image.value.crossOrigin = 'Anonymous'; // 处理跨域问题
  image.value.src = url;
  image.value.onload = () => {
    ctx.value.drawImage(image.value, 0, 0, canvas.value.width, canvas.value.height);
    originalImageData.value = ctx.value.getImageData(0, 0, canvas.value.width, canvas.value.height);
    const base64DataURL = canvas.value.toDataURL('image/png');
    api.addroom({
      key: store.roomid,
      // "B2": num.value-chooseitems.value.length,
      "BBBB": base64DataURL
    }).then((res) => {
      console.log(res);
    })
  };
};


// 获取用户点击的颜色
const pickColor = (event) => {
  const rect = canvas.value.getBoundingClientRect();
  console.log(rect);
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
 
  const pixel = ctx.value.getImageData(x, y, 1, 1).data;
  const pickedColor = { r: pixel[0], g: pixel[1], b: pixel[2] };
  console.log(rgbToHex(pixel[0], pixel[1], pixel[2]));

  num.value++;
  let xx = 0;
  if (colormap.get(rgbToHex(pixel[0], pixel[1], pixel[2])) == replacementColor.value) {
    replaceColor(pickedColor);
    colornum.value++;


    if (colornum.value == chooseitems.value.length) {
      xx = 1;
      emits('next', num.value - chooseitems.value.length);
      api.addroom({
        key: store.roomid,
        "B2": "ok"
      }).then((res) => {
        console.log(res);
      })
    }
  } else if (replacementColor.value != '') {
    message.error("选择错误")
    const errorSound = document.getElementById('errorSound');
    errorSound.play();
    console.log("error");

  }
  if (xx == 0) {
    const base64DataURL = canvas.value.toDataURL('image/png');
    api.addroom({
      key: store.roomid,
      "B2": num.value - chooseitems.value.length,
      "BBBB": base64DataURL
    }).then((res) => {
      console.log(res);
    })
  }

};

// 替换选定颜色的方法
const replaceColor = (pickedColor) => {

  const imageData = ctx.value.getImageData(0, 0, canvas.value.width, canvas.value.height);
  const data = imageData.data;
  const targetColor = hexToRgb(replacementColor.value);

  for (let i = 0; i < data.length; i += 4) {
    if (data[i] === pickedColor.r && data[i + 1] === pickedColor.g && data[i + 2] === pickedColor.b) {
      data[i] = targetColor.r;
      data[i + 1] = targetColor.g;
      data[i + 2] = targetColor.b;
    }
  }

  ctx.value.putImageData(imageData, 0, 0);


};

// 将十六进制颜色转换为 RGB 格式
const hexToRgb = (hex) => {
  const bigint = parseInt(hex.slice(1), 16);
  const r = (bigint >> 16) & 255;
  const g = (bigint >> 8) & 255;
  const b = (bigint & 255);
  return { r, g, b };
};
// 将rgb颜色转换为 十六进制 格式
function rgbToHex(r, g, b) {
  // 将每个颜色值转换为16进制字符串，并确保其长度为2
  const toHex = (color) => {
    const hex = color.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };

  // 拼接结果
  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

// 下载处理后的图像
const downloadImage = () => {
  const link = document.createElement('a');
  link.href = canvas.value.toDataURL('image/png');
  link.download = 'canvas-image.png';
  link.click();
};


</script>

<style lang="scss" scoped>
.game2B {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 2rem;

  .desc {
    font-size: 3rem;
  }

  .btns {
    display: flex;
    gap: 2rem;

    .item {
      height: 6rem;
      width: 6rem;
    }
  }
}

</style>